﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.ADF.Web.UI.WebControls;
using ESRI.ArcGIS.ADF.Web.DataSources;
using System.Collections;
using System.Data;
using ESRI.ArcGIS.ADF.Web;
//using GIS.utils;
using ESRI.ArcGIS.ADF.Web.Display.Graphics;
using ESRI.ArcGIS.ADF.Web.Geometry;
using BTGISWASECO.BusinessEntities;
using BTGISWASECO.DataLayer;
using Microsoft.Office.Interop.Excel;
using ESRI.ArcGIS.Server;
using System.Reflection;

public partial class PresentationLayer_ThongKeBaoCao : System.Web.UI.Page
{
    DataAccessHelper db = new DataAccessHelper();
    public int selectLayerIndex;
    public int selectSearchLayerIndex;
    List<ESRI.ArcGIS.Geodatabase.IFeatureClass> LfeatureClass= new List<ESRI.ArcGIS.Geodatabase.IFeatureClass>();
    List<ESRI.ArcGIS.Carto.ILayer> LILayer = new List<ESRI.ArcGIS.Carto.ILayer>();
    public System.Data.DataTable dTable = new System.Data.DataTable();
    protected string fieldsClause;//System.Data.DataTable
    protected int widestData;

    OngPhanPhoiEntities ongPhanPhoiEntities = new OngPhanPhoiEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        widestData = 0;
        updateLayerList();
        if(!IsPostBack)
        updateFieldList();     
    }

    private void updateLayerList()
    {
         ESRI.ArcGIS.Geodatabase.IWorkspace workspace;
            ESRI.ArcGIS.Server.IServerContext serverContext = db.ServerDatabaseSDE();
            ESRI.ArcGIS.Geodatabase.IWorkspaceEdit workspaceEdit = null;
            ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass;
            
            ESRI.ArcGIS.Carto.IFeatureLayer iFeatureLayer = null;
            ESRI.ArcGIS.esriSystem.UID pUID = new ESRI.ArcGIS.esriSystem.UIDClass();
            ESRI.ArcGIS.Geodatabase.IEnumDatasetName EnumDSName;
            ESRI.ArcGIS.Geodatabase.IDatasetName _IDatasetName;            
            try
            {
                ESRI.ArcGIS.esriSystem.IPropertySet propertySet_Connection = (ESRI.ArcGIS.esriSystem.IPropertySet)serverContext.CreateObject("esriSystem.PropertySet");//tham khảo một ví dụ SDE, thay đổi các giá trị này
                propertySet_Connection.SetProperty("server", "localhost");
                propertySet_Connection.SetProperty("instance", "5151");
                propertySet_Connection.SetProperty("database", "BTGISWASECO");
                propertySet_Connection.SetProperty("user", "sde");
                propertySet_Connection.SetProperty("password", "123");
                propertySet_Connection.SetProperty("version", "sde.DEFAULT");
                ESRI.ArcGIS.Carto.IMapServer mapServer = serverContext.ServerObject as ESRI.ArcGIS.Carto.IMapServer;
                ESRI.ArcGIS.Carto.IMapServerObjects mapServerObjects = mapServer as ESRI.ArcGIS.Carto.IMapServerObjects;
                ESRI.ArcGIS.Carto.IMap aoMap = mapServerObjects.get_Map(mapServer.DefaultMapName);
                #region thu
                //ESRI.ArcGIS.Carto.IEnumLayer el = aoMap.get_Layers(null, true);
                //ESRI.ArcGIS.Carto.ILayer layer = null;
                //layer = el.Next();
                ////Loop through all the layers till it gets the Notification ( Jobs ) Spatial layer
                //while (layer != null)
                //{
                //    string ly = layer.Name;
                   
                //    layer = el.Next();
                //}
                #endregion thu
                ESRI.ArcGIS.Geodatabase.IWorkspaceFactory2 workspaceFactory = (ESRI.ArcGIS.Geodatabase.IWorkspaceFactory2)serverContext.CreateObject("esriDataSourcesGDB.SdeWorkspaceFactory");
                //ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass();
                workspace = workspaceFactory.Open(propertySet_Connection, 0);

                ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace;
                ESRI.ArcGIS.Geodatabase.IEnumDataset iEnumDataset = workspace.get_Datasets(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTAny);
                // ESRI.ArcGIS.Geodatabase.IEnumDataset dsenum1 = workspace.get_Datasets(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTFeatureDataset);
                // ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWS = workspace as ESRI.ArcGIS.Geodatabase.IFeatureWorkspace;
                ESRI.ArcGIS.Geodatabase.IEnumDatasetName iEnumDatasetName = workspace.get_DatasetNames(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTAny);

                ESRI.ArcGIS.Geodatabase.IDatasetName iDatasetName = iEnumDatasetName.Next();
                if (DListLop.SelectedIndex > 0)
                    selectLayerIndex = DListLop.SelectedIndex;             
                DListLop.Items.Clear();

                while (iDatasetName != null)
                {
                    if (iDatasetName.Category == "SDE Feature Class")
                    {
                        if (iDatasetName.Name == "BTGISWASECO.SDE.wDataLogger")
                        {
                            featureClass = featureWorkspace.OpenFeatureClass(iDatasetName.Name);
                            break;
                        }
                    }
                    else
                        if (iDatasetName.Name == "BTGISWASECO.SDE.WaterDistribution")
                        {
                            EnumDSName = iDatasetName.SubsetNames;
                            _IDatasetName = EnumDSName.Next();
                          
                            while (_IDatasetName != null)
                            {
                                if (_IDatasetName.Category != "BTGISWASECO.SDE.WaterDistribution")
                                {
                                    featureClass=featureWorkspace.OpenFeatureClass(_IDatasetName.Name);

                                    LfeatureClass.Add(featureClass);
                                    //LfeatureClass.Insert(k,featureWorkspace.OpenFeatureClass(_IDatasetName.Name));                             
                                    DListLop.Items.Add(new ListItem(featureClass.AliasName, _IDatasetName.Name));
                                    //if (_IDatasetName.Name == "BTGISWASECO.SDE.wOngPhanPhoi")
                                    //{
                                    //    BTGISWASECO.Search.AttributeSearcher Atrs = new BTGISWASECO.Search.AttributeSearcher(featureClass as ESRI.ArcGIS.Geodatabase.ITable);
                                    //    dTable=Atrs.ResultTable();
                                    //}
                                
                                }
                                _IDatasetName = EnumDSName.Next();
                            }
                            if (selectLayerIndex < DListLop.Items.Count)
                            {
                                DListLop.SelectedIndex = selectLayerIndex;
                                //bindDataToGridView(LfeatureClass[0]);
                            }

                        }
                    iDatasetName = iEnumDatasetName.Next();
                }
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
            finally
            {
                if (workspaceEdit != null)
                {
                    if (workspaceEdit.IsBeingEdited())
                        workspaceEdit.StopEditing(false);
                }
                if (serverContext != null)
                    serverContext.ReleaseContext();
            }
        }


    protected void DListLop_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListBTruongTK.Items.Clear();
        updateFieldList();
    }

    private void updateFieldList()
    {
        ListBTruongLop.Items.Clear();
        ESRI.ArcGIS.Geodatabase.IFeatureClass iFrClass=null;
        foreach(var itemFclas in LfeatureClass)
        {
            if (DListLop.SelectedItem.Text == itemFclas.AliasName)
            {
                iFrClass = itemFclas;
                break;
            }
        }
        int t = iFrClass.Fields.FieldCount;
        for (int i = 0; i < iFrClass.Fields.FieldCount; i++)
        {
            if ((!iFrClass.Fields.get_Field(i).Name.Equals("SHAPE")) && (!iFrClass.Fields.get_Field(i).Name.Equals("SHAPE.len")) && (!iFrClass.Fields.get_Field(i).Name.Equals("SHAPE.area")))
            {
                ListItem iteml = new ListItem(iFrClass.Fields.get_Field(i).AliasName,iFrClass.Fields.get_Field(i).Name);
                ListBTruongLop.Items.Add(iteml);
            }

            
        }
    
    }


    public void bindDataToGridView(ESRI.ArcGIS.Geodatabase.IFeatureClass featureclass)
    {
        BTGISWASECO.Search.AttributeSearcher Atrs = new BTGISWASECO.Search.AttributeSearcher(featureclass as ESRI.ArcGIS.Geodatabase.ITable);
        dTable = Atrs.ResultTable();
        //GridViewData.Columns.Clear();
        //foreach (DataColumn column in dTable.Columns)
        //{
        //    BoundField field = new BoundField();
        //    field.DataField = column.ColumnName;
        //    field.HeaderText = column.ColumnName;
        //    GridViewData.Columns.Add(field);
        //}
        GridViewData.DataSource = dTable;
        GridViewData.DataBind();
        //if (GridViewData.Rows.Count > 0)
        //    GridViewData.Rows[0].Cells[0].Width = 1000;
        for (int i = 12; i < this.GridViewData.Columns.Count - 1; i++)
        {
            this.GridViewData.Columns[i].Visible = false;
            //this.GridViewData.MasterGridViewTemplate.Columns[i].MaxWidth = 60;
            //this.GridViewData.MasterGridViewTemplate.Columns[i].Width = 60;
        }
    }


    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (ListBTruongLop.Items.Count > 0 && ListBTruongLop.SelectedIndex > -1)
            if (ListBTruongLop.SelectedValue.ToString() != "")
            {
                while (ListBTruongLop.Items.Count > 0 && ListBTruongLop.SelectedItem != null)
                {
                    ListItem selectedItem = ListBTruongLop.SelectedItem;
                    selectedItem.Selected = false;
                    ListBTruongTK.Items.Add(selectedItem);
                    ListBTruongLop.Items.Remove(selectedItem);
                }

            }       
    }
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        if (ListBTruongTK.Items.Count > 0 && ListBTruongTK.SelectedIndex > -1)
            while (ListBTruongTK.Items.Count > 0 && ListBTruongTK.SelectedItem != null)
            {
                ListItem selectedItem = ListBTruongTK.SelectedItem;
                selectedItem.Selected = false;
                ListBTruongLop.Items.Add(selectedItem);
                ListBTruongTK.Items.Remove(selectedItem);
            }     
    }

    protected void btnExcel_Click(object sender, EventArgs e)
    {
        #region khai bao
        
        string stDXuatExcelHeader = string.Empty;
        string stOutput = "";
        int count = 0;
        #endregion khai bao

        try
        {

            foreach (var itemFclas in LfeatureClass)
            {
                if (DListLop.SelectedItem.Text == itemFclas.AliasName)
                {
                    BTGISWASECO.Search.AttributeSearcher Atrs = new BTGISWASECO.Search.AttributeSearcher(itemFclas as ESRI.ArcGIS.Geodatabase.ITable);
                    dTable = Atrs.ResultTable();
                }
            }
            HttpContext context = HttpContext.Current;
            context.Response.Clear(); // xóa rỗng khoảng nhớ tạm thời để ghi dữ liệu
            context.Response.ContentEncoding = System.Text.Encoding.Unicode;
            context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

            #region thu dua vao datatable
            //for (int t = 0; t < ListBTruongTK.Items.Count; t++)
            //{
            //    context.Response.Write(ListBTruongTK.Items[t].Text + "\t");
            //}
            //context.Response.Write(Environment.NewLine);
            foreach (DataRow dtRow in dTable.Rows)
            {
                string stXuatExcel = string.Empty;
                foreach (DataColumn column in dTable.Columns)
                {
                    for (int k = 0; k < ListBTruongTK.Items.Count; k++)
                    {
                        if (ListBTruongTK.Items[k].Text == column.ColumnName)
                        {
                            if (count < ListBTruongTK.Items.Count)
                            {
                                stDXuatExcelHeader = stDXuatExcelHeader + column.ColumnName + "\t";
                                stOutput = stDXuatExcelHeader + "\r\n";
                            }
                            count = count + 1;
                            stXuatExcel = stXuatExcel + dtRow[column].ToString() + "\t";                            
                        }
                    }
                }
                stOutput += stXuatExcel + "\r\n";
            }
            context.Response.Write(stOutput);
            //context.Response.Write(Environment.NewLine);
            //context.Response.Write(stXuatExcel + "\r\n");
            //context.Response.Write(Environment.NewLine);
           context.Response.AddHeader("content-disposition", "attachment; filename=" + "Report Online GIS" + ".xls");
           context.Response.ContentType = "application/vnd.ms-excel";
           context.Response.End();
                #endregion thu
        }
        catch (System.Exception exception)
        {
            throw exception;
        }


    }
     
    public System.Data.DataTable ConvertITable(ESRI.ArcGIS.Geodatabase.ITable table)
    {

        System.Data.DataTable ExpertInfo;
        ExpertInfo = new System.Data.DataTable("ExpertInfo");

        try
        {
            ESRI.ArcGIS.Geodatabase.IQueryFilter que = new ESRI.ArcGIS.Geodatabase.QueryFilterClass();
            ESRI.ArcGIS.Geodatabase.ICursor pCursor = table.Search(null, false);
            ESRI.ArcGIS.Geodatabase.IRow pRow = pCursor.NextRow();

            if (pRow != null)
            {
                for (int i = 0; i < pRow.Fields.FieldCount; i++)
                {
                    ExpertInfo.Columns.Add(pRow.Fields.get_Field(i).Name);
                }
                while (pRow != null)
                {
                    DataRow pDataRow = ExpertInfo.NewRow();
                    for (int j = 0; j < pCursor.Fields.FieldCount; j++)
                        pDataRow[j] = pRow.get_Value(j);
                    ExpertInfo.Rows.Add(pDataRow);
                    pRow = pCursor.NextRow();
                }
            }
        }
        catch (System.Exception ex)
        {
            throw ex;
        }

        return ExpertInfo;
    }

    protected void GridViewData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridViewData.PageIndex = e.NewPageIndex;
        bindDataToGridView((ESRI.ArcGIS.Geodatabase.IFeatureClass)dTable);
    }
    protected void GridViewData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewData.Columns[1].ItemStyle.Width = 50;
                GridViewData.Columns[2].ItemStyle.Width = 150;
            }
        }
    }

    protected void btnAddAll_Click(object sender, EventArgs e)
    {
        AddAll(ListBTruongLop, ListBTruongTK);
    }

    void AddAll(System.Web.UI.WebControls.ListBox src, System.Web.UI.WebControls.ListBox dst)
    {
        for (int i = 0; i < src.Items.Count; i++)
        {
            ListItem a = src.Items[i];
            src.Items.Remove(a);
            dst.Items.Add(a);
            i--;
        }
    }
    protected void btnRemoveAll_Click(object sender, EventArgs e)
    {
        AddAll(ListBTruongTK,ListBTruongLop);
    }
}